package com.example.a1.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;

public class ClickableViewPager extends ViewPager {
    private OnItemClickListener onItemClickListener;
    private float downX, downY;
    private static final int CLICK_THRESHOLD = 5; // 点击阈值（防止滑动误判为点击）

    public ClickableViewPager(Context context) {
        super(context);
    }

    public ClickableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    // 点击事件回调接口
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    // 设置点击监听器
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    // 处理触摸事件，识别点击动作
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = ev.getX();
                downY = ev.getY();
                break;
            case MotionEvent.ACTION_UP:
                float upX = ev.getX();
                float upY = ev.getY();
                // 距离小于阈值，判定为点击
                if (Math.abs(upX - downX) < CLICK_THRESHOLD && Math.abs(upY - downY) < CLICK_THRESHOLD) {
                    if (onItemClickListener != null) {
                        int currentPosition = getCurrentItem() % getAdapter().getCount();
                        onItemClickListener.onItemClick(currentPosition);
                    }
                    return true;
                }
                break;
        }
        return super.onTouchEvent(ev);
    }
}